package com.cy.loader;

import com.cy.container.Wrapper;
import com.cy.server.Request;
import com.cy.server.Response;

import java.lang.reflect.Method;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Author ChenYan
 * @Date 2021/8/13 17:15
 * @Description
 */
public class MyClassLoader extends ClassLoader{

    public static MyClassLoader instance = new MyClassLoader();

    public static MyClassLoader getInstance(){
        return instance;
    }

    public void invokeOtherMethod(String classAbsolutePath, String classPath, Request request, Response response){
        classAbsolutePath = "file:///D:/webapps/test1/com/test/Test1Servlet.class";
        classPath = "com.test.Test1Servlet";
        System.out.println(classAbsolutePath);
        byte[] cLassBytes = null;
        Path path = null;
        try {
            path = Paths.get(new URI(classAbsolutePath));
            cLassBytes = Files.readAllBytes(path);

            Class clazz = defineClass(classPath, cLassBytes, 0, cLassBytes.length);
            Object obj = clazz.newInstance();
            Method method = clazz.getMethod("service", new Class[]{Request.class, Response.class});
            method.invoke(obj, request, response);
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void loadClassAndMethod(Wrapper wrapper) {
        String classAbsolutePath = wrapper.getPath();
        String classPath = wrapper.getServletClass();
        System.out.println(classAbsolutePath);
        byte[] cLassBytes = null;
        Path path = null;
        try {
            path = Paths.get(new URI(classAbsolutePath));
            cLassBytes = Files.readAllBytes(path);

            Class clazz = defineClass(classPath, cLassBytes, 0, cLassBytes.length);
            Object obj = clazz.newInstance();
            wrapper.setObj(obj);
            Method method = clazz.getMethod("service", new Class[]{Request.class, Response.class});
            wrapper.setMethod(method);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
